#!/usr/bin/python

# Raspberry Pi <-> MCP3008 Hardware SPi communication
#
# Requires:
#
#       in /etc/modprobe.d/raspi-blacklist.conf
#           #blacklist spi-bcm2708     <= Must be commented out! Need reboot for changes
#
#       spidev + py-spidev (http://github.com/doceme/py-spidev)
#           git clone http://github.com/doceme/py-spidev
#           cd ./py-spidev
#           python setup.py install
#
# MCP3008  <--> RPi GPIO
#   Dout         MISO
#   Din          MOSI
#   CLK          SCLK
#   CS           CE0   (CableSelect)
#   VCC          3.3V
#   VREF         3.3V
#   GND          GND
#   AGND         GND
#
#
# Analog Input:
#
# I used i Force Sensitive Resistor, but any resistive device would do the trick. A trim pot for example.
#
#     [MCP3008 CH0]--+
#                    |
# [GND]--[R 10kOmh]--+--[FSR]--[RPi 3.3V]

try: 
    import RPi.GPIO as GPIO
except RuntimeError:
    print "Error while trying to load GPIO module, try running the script with superuser privileges!"


import spidev                                           # SPI Hardware communication Module
import time

if __name__ == "__main__":
    spiDevice = spidev.SpiDev()                         # Create a spidev Object
    channel = 0
    
    while True:
        spiDevice.open(0,0)                             # Open communication with SPI device conected to CE0 (/dev/spidev0.0)
        values = spiDevice.xfer2([1,(8+channel)<<4,0])  # Sends 3 bytes (required for MCP3008, 128=>channel 0), returns a list of 3 bytes as values
        index = ((values[1]&3) << 8) + values[2]        # 10 bit coded value
        print "O" * int(index*20/1023.) + "-" * (20-int(index*20/1023.))
        time.sleep(0.09)
        spiDevice.close()                               # Close device, required to prevent "Too many IO files open" error
    
    
    
